﻿using System;
using Deepcode.Flux.Core.Systems.CMS;
using MVCStore.Views.Page;

namespace MVCStore.Models
{
	/// <summary>
	/// Provider to get content out of Flux as required
	/// </summary>
	public class ContentModel
	{
		public PageModel GetHelpCentre()
		{
			ContentQuery query = new ContentQuery();

			// Get the "Page" content item under /content/articles/ with the name "HelpHome"
			query.BaseMatch.AND(new StaticFieldMatch(ContentStaticField.Path, ContentQueryOperator.EQ, "/content/articles/"));
			query.BaseMatch.AND(new StaticFieldMatch(ContentStaticField.ContentType, ContentQueryOperator.EQ, "Page"));
			query.BaseMatch.AND(new StaticFieldMatch(ContentStaticField.Name, ContentQueryOperator.EQ, "HelpHome"));

			// Ensure we have a matching row
			ContentObject [] results = query.GetMatching();
			if (results.Length < 1)
				throw new InvalidOperationException("/content/articles/HelpHome page content does not exist");

			return CreatePageModelForNode(results[0]);
		}

		public PageModel GetPageForNodeId(int nodeId)
		{
			ContentObject node = ContentQuery.GetByID(nodeId);

			// Ensure we have a matching row
			if (node == null)
				throw new InvalidOperationException("content does not exist");

			return CreatePageModelForNode(node);
		}

		private PageModel CreatePageModelForNode(ContentObject node)
		{
			int parentNodeId = -1;
			
			// Only specify a parent IF it's also an item of content
			if (node.ParentLive.FK_STypeID == "Page")
				parentNodeId = node.FK_ParentID;

			PageModel result = new PageModel
			{
				ContentNodeId = node.PK_ID,
				PageContent = node.Fields["body"].Replace("\n", "<br/>"),
				PageTitle = node.NodeTitle,
				ParentNodeId = parentNodeId
			};

			foreach (ContentObject child in node.ChildrenLive)
				result.AddChild(child.PK_ID, child.NodeTitle);

			return result;
		}
	}
}
